package com.ct.boot.launch.service;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;

import java.io.IOException;
import java.util.Properties;

/**
 * @Auther: Charles chen
 * @Date: 2020/7/14 17:48
 * @Description: 以数据源的形式加载配置文件
 */
public class MixPropertySourceFactory  extends DefaultPropertySourceFactory {
    @Override

    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
//return super.createPropertySource(name, resource);配置文件名字 资源文件对象
        String sourceName=name!=null?name:resource.getResource().getFilename();
        if (sourceName!=null&&(sourceName.endsWith(".yml"))){
            Properties propertiesFormYaml=loadYml(resource);
            return new PropertiesPropertySource(sourceName,propertiesFormYaml);
        }else{
            return super.createPropertySource(name,resource);
        }
    }
    private Properties loadYml(EncodedResource resource){
        YamlPropertiesFactoryBean factory=new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }
}
